//GoodsController.java
package org.example.examtemplate01.Controller;

import org.example.examtemplate01.Service.GoodsService;
import org.example.examtemplate01.module.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/Goods")
public class GoodsController {

    @Autowired
    GoodsService goodsService;

    //获取goods列表
    @RequestMapping("/list")
    public String List(Model model) {
        //1.
        List<Goods> goodsList = goodsService.fetchGoodsList();
        //2.
        model.addAttribute("goodsList",goodsList);
        //3.
        return "GoodsList";
    }

    //删除对应ID的goods
    @RequestMapping("remove")
    public String remove(int id){
        goodsService.removeGoodsById(id);
        return "redirect:/Goods/list/1/3";
    }

    //准备新增Goods &
    // 获取Goods列表(因为要跳转到另一个页面，所以要重新获取并传递数据至新页面，以便让Thymeleaf模板渲染) &
    // 同时跳转新增Goods的页面
    @RequestMapping("toAdd")
    public String toAdd(Model model){
        List<Goods> goodsList = goodsService.fetchGoodsList();
        model.addAttribute("goodsList",goodsList);
        return "AddGoods";
    }

    //新增Goods
    @RequestMapping("add")
    public String add(Goods goods){
        goodsService.add(goods);
        return "redirect:/Goods/list/1/3";
    }

    //准备修改Goods & 查询对应ID的Goods & 同时跳转至修改Goods的页面
    @RequestMapping("toEdit")
    public String toEdit(int id, Model model){
        Goods oldGoods = goodsService.fetchGoodsById(id);
        model.addAttribute("oldGoods",oldGoods);
        return "EditGoods";
    }

    //修改Goods
    @RequestMapping("edit")
    public String edit(Goods goods){
        goodsService.edit(goods);
        return "redirect:/Goods/list/1/3";
    }

    //分页获取goods列表
    @RequestMapping("list/{currentPage}/{pageSize}")
    //    @PathVariable 用于从 URL 路径中提取变量值并赋值给方法的参数
    public String list(Model model, @PathVariable("currentPage") int currentPage, @PathVariable("pageSize") int pageSize){
        if(currentPage < 1) currentPage = 1;
        if(pageSize < 1) pageSize = 3;
        //分页获取goods列表的同时，将当前页和总页数等参数传递
        List<Goods> goodsList = goodsService.fetchByPage(currentPage, pageSize);
        model.addAttribute("goodsList",goodsList);
        return "GoodsList";
    }
}
